package crosstime.android.cexplorer;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.content.Context;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import crosstime.android.interfaces.ISelectController;

public class BaseFileListAdapter extends BaseAdapter implements ISelectController{

	protected File mCurrentDir = new File("/");
	protected File mOldDir = new File("/");
	protected LayoutInflater mInflater 	 = null;
	protected ArrayList<FileObject> mFileList = new ArrayList<FileObject>();
	protected Context mContext = null;
	protected boolean mIsGridView = true;
	public BaseFileListAdapter(Context context){
		mInflater = LayoutInflater.from(context);
		mContext = context;
		reloadList();
		sortByNameOrder();
	}
	
	public void setAdapterType(boolean isGridView){
		mIsGridView = isGridView;
	}
	
	@Override
	public int getCount() {
		return mFileList.size();
	}
	@Override
	public Object getItem(int position) {
		return mFileList.get(position);
	}
	@Override
	public long getItemId(int position) {
		return position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if(convertView == null)
		{
			holder = new ViewHolder();
			if(mIsGridView)
				convertView = mInflater.inflate(R.layout.file_item, null);
			else
				convertView = mInflater.inflate(R.layout.file_list_item, null);
			holder.icon = (ImageView) convertView.findViewById(R.id.file_icon);
			holder.text = (TextView) convertView.findViewById(R.id.file_desc);	
			convertView.setTag(holder);
		}
		else
			holder = (ViewHolder) convertView.getTag();
		FileObject li = mFileList.get(position);
		String text = li.Name;
		holder.text.setText(text);
		int icon = li.IconId;
		holder.icon.setImageResource(icon);
		if(li.mSelectMode == FileObject.MODE_NONE)
			convertView.setBackgroundResource(0);
		else if(li.mSelectMode == FileObject.MODE_SELECTED)
			convertView.setBackgroundResource(R.drawable.fileitem_selected);
		else if(li.mSelectMode == FileObject.MODE_TO_CUT)
			convertView.setBackgroundResource(R.drawable.fileitem_cut);
		return convertView;
	}

	public String getFilePathByPosition(int position){
		if(position >= mFileList.size())
			return mCurrentDir.getAbsolutePath();

		return mFileList.get(position).Path;
	}
	
	public boolean changeDirectory(String strPath){
		File dir = new File(strPath);
		if(dir.exists() && dir.isDirectory())
		{
			mOldDir = mCurrentDir;
			mCurrentDir = dir;
			if(!reloadList())
			{
				mCurrentDir = mOldDir;
				return false;
			}
			else
				notifyDataSetChanged();
			return true;
		}else
			return false;
	}
	
	public boolean openParentFolder(){
		String parent = mCurrentDir.getParent();
		if(parent == null)
			return false;
		return changeDirectory(parent);
	}
	
	protected boolean reloadList(){
		File[] fileList = mCurrentDir.listFiles();
		if(fileList == null)
			return false;
		mFileList.clear();
//		if(mCurrentDir.getParent() != null)
//			mFileList.add(new ListItem(mCurrentDir.getParentFile(), ListItemUtil.TYPE_UPLEVEL));
		for(File file : fileList){
			mFileList.add(new FileObject(file));
		}
		sortByNameOrder();
		return true;
	}

	private boolean bReverseOrder = false;
	public void switchReverseOrder(){
		bReverseOrder = !bReverseOrder;
		reloadList();
		notifyDataSetChanged();
	}
	protected void sortByNameOrder(){
		Collections.sort(mFileList, new Comparator<FileObject>() {

			@Override
			public int compare(FileObject obj1, FileObject obj2) {

				if(obj1 != null && obj2 != null)
				{
					boolean isDir1 = obj1.isDirectory(); 
					boolean isDir2 = obj2.isDirectory();
					
					if(obj1.Name.equals(".."))
						return -1;
					if(obj2.Name.equals(".."))
						return 1;

					if(isDir1 && !isDir2)
						return -1; //obj1 ahead of obj2
					else if(!isDir1 && isDir2)
						return 1;
					int res = obj1.Name.compareTo(obj2.Name);
					return bReverseOrder? -res : res;  
				}
				return 0;
			} });  
	}
	
	protected class ViewHolder{
		public ImageView icon;
		public TextView text;
	}

	public class FileObject{
		public final static int MODE_NONE = 0;
		public final static int MODE_SELECTED = 1;
		public final static int MODE_TO_CUT = 2;
		public final static int MODE_TO_DEL = 3;
		
		public int IconId;
		public String Path;
		public String Name;
		public int mSelectMode;
		public FileObject(File file){
			Path = file.getAbsolutePath();
			Name = file.getName();
			IconId = getIconIdByType(Path);
			mSelectMode = MODE_NONE;
		}
		
		private int getIconIdByType(String fileName){
			
			File file = new File(fileName);
			if(file.isDirectory())
				return ICON_DIR;
			
			int lastDot = fileName.lastIndexOf(".");
			if(lastDot == -1)
				return ICON_UNKNOWN;
			
			String ext = fileName.substring(lastDot).toLowerCase();
			int size = knownType.length;
			for(int i = 0; i < size; i++){
				if(ext.equals(knownType[i]))
					return knownIconId[i];
			}
			
			return ICON_UNKNOWN; 
		}
		
		public boolean isDirectory(){
			File file = new File(Path);
			return file.exists() && file.isDirectory();
		}
		
		private final String knownType[] = {".jpg", ".txt"}; 
		private final int knownIconId[] = { R.drawable.icon, R.drawable.icon_txt};
		public final static int ICON_DIR 		= R.drawable.icon_folder;
		public final static int ICON_UNKNOWN 	= R.drawable.icon_unknown;
	}

	public ArrayList<Integer> mSelectedIndex = new ArrayList<Integer>();
	private int mMode = MODE_OFF;
	private ViewGroup mDisplayView = null;
	
	@Override
	public void select(Rect selectRect) {
		if(mDisplayView == null)
			return;
		if(mMode == MODE_ON)
		{
			clearSelectStates();
		}

		int count = mDisplayView.getChildCount();
		Rect viewRect = new Rect();
		for(int i =0; i< count; i++)
		{
			View v = mDisplayView.getChildAt(i);
			v.getHitRect(viewRect);
			if(viewRect.intersect(selectRect))
			{
				if(mMode == MODE_ON_PLUS || mMode == MODE_ON)
				{
					addSelectedToList(i);
					v.setBackgroundResource(R.drawable.fileitem_selected);
				}
				else if(mMode == MODE_ON_MINUS)
				{
					removeSelectedFromList(i);
					v.setBackgroundResource(0);
				}

				v.invalidate();
			}
		}
	}


	@Override
	public int getMode() {
		return mMode;
	}

	@Override
	public void setMode(int mode) {
		if(mode == MODE_OFF)
			clearSelectStates();
		mMode = mode;
	}

	@Override
	public void setCutMode(){
		int count = mSelectedIndex.size();
		if(count > 0)
			setMode(MODE_CUT);
		for(int i =0; i< count; i++)
		{
			View v = mDisplayView.getChildAt(mSelectedIndex.get(i));
			mFileList.get(mSelectedIndex.get(i)).mSelectMode = FileObject.MODE_TO_CUT;
			v.setBackgroundResource(R.drawable.fileitem_cut);
			v.invalidate();
		}
	}

	@Override
	public void setDisplayViewGroup(ViewGroup v) {
		mDisplayView = v;
	}
	
	private void addSelectedToList(Integer index){
		if(mSelectedIndex.indexOf(index) == -1)
		{
			mSelectedIndex.add(index);
			mFileList.get(index).mSelectMode = FileObject.MODE_SELECTED;
		}
	}
	
	private void removeSelectedFromList(Integer index){
		if(mSelectedIndex.indexOf(index) != -1)
		{
			mSelectedIndex.remove(index);
			mFileList.get(index).mSelectMode = FileObject.MODE_NONE;
		}
	}
	
	private void clearSelectStates(){
		int count = mSelectedIndex.size();
		for(int i =0; i< count; i++)
		{
			int index = mSelectedIndex.get(i);
			View v = null;
			if(index < mDisplayView.getChildCount())
				v = mDisplayView.getChildAt(index);
			
			mFileList.get(index).mSelectMode = FileObject.MODE_NONE;
			if(v != null)
			{
				v.setBackgroundResource(0);
				v.invalidate();
			}
		}
		mSelectedIndex.clear();
	}
}
